package com.qf.producer.ps;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        //构建一个连接工厂(配置和rabbitmq的连接信息)
        ConnectionFactory factory = new ConnectionFactory();
        //设置rabbitmq的机器ip
        factory.setHost("localhost");
        //设置rabbitmq运行的端口
        factory.setPort(5672);
        //设置登录用户名
        factory.setUsername("guest");
        //设置登录密码
        factory.setPassword("guest");
        //设置写入数据的虚拟主机
        factory.setVirtualHost("cdm");

        //获取Connection对象
        Connection conn = factory.newConnection();
        //获取channel
        Channel channel = conn.createChannel();

        //利用channel发送消息
        //① 声明两个个队列
        channel.queueDeclare("ps.que1",true,false,false,null);
        channel.queueDeclare("ps.que2",true,false,false,null);

        //② 声明一个交换机
        /*
            String exchange, 交换机名称
            BuiltinExchangeType type, 交换机类型 (fanout、direct、topic)
            boolean durable, 是否支持消息持久化
            boolean autoDelete, 是否自动删除
            boolean internal, 是否是内部交换机
            Map<String, Object> arguments  额外参数

            String exchange, String type, boolean durable
         */
        channel.exchangeDeclare("ps.ex", BuiltinExchangeType.FANOUT,true);

        //③ 绑定交换机和队列的关系
        /*
            String queue 队列名称
            String exchange 交换机名称
            String routingKey 路由键  (对于FANOUT类型的交换机，在进行消息路由时，不会看路由键,将消息路由到所有跟他绑定的队列上)
            Map<String, Object> arguments 额外参数
         */
        channel.queueBind("ps.que1","ps.ex","");
        channel.queueBind("ps.que2","ps.ex","");

        //④ 向队列中发送消息
        channel.basicPublish("ps.ex","",null,"我是发布订阅模式的消息".getBytes(StandardCharsets.UTF_8));

        //释放资源
        channel.close();
        conn.close();
    }
}
